import CryptoJS from 'crypto-js';
// const { SHA1, md5 } = CryptoJS;

export const useUserStore = defineStore('user', {
    state: () => ({
        _id: "",
        nickname: "",
        avatar: "",
        loginLog: {},
    }),
    persist: {
        // storage: persistedState.localStorage,
    },
    actions: {
        async signIn(params: Record<string, any> = {}) {
            const config = useRuntimeConfig();
            const system = useSystemStore();
            params.systemInfo = system.deviceInfo;

            params.password = CryptoJS.MD5(params.password).toString(CryptoJS.enc.Hex);


            // 设置请求选项
            const requestOptions = {
                baseURL: config.public.apiUrl, // 设置 baseURL
                method: "POST" as const,
                headers: {"X-APP-USER-TOKEN": ""},
                body: params,
            };

            try {
                // 发起请求
                const {data, error} = await useFetch("user/signIn", requestOptions);

                // 处理响应数据
                if (!error.value) {
                    //@ts-ignore
                    const {_id, nickname, avatar, loginLog} = data.value;
                    this._id = _id;
                    this.nickname = nickname;
                    this.avatar = avatar;
                    this.loginLog = loginLog;

                    return {data: data.value, error: null};
                }

                return {data: null, error: error};
            } catch (err) {
                console.error('request error', err);
                return {data: null, error: err};
            }
        },
        async signUp(params: Record<string, any> = {}) {
            const config = useRuntimeConfig();
            const system = useSystemStore();
            params.systemInfo = system.deviceInfo;

            params.password = CryptoJS.MD5(params.password).toString(CryptoJS.enc.Hex);
            params.repeatPassword = CryptoJS.MD5(params.repeatPassword).toString(CryptoJS.enc.Hex);

            const requestOptions = {
                baseURL: config.public.apiUrl, // 设置 baseURL
                method: "POST" as const,
                headers: {"X-APP-USER-TOKEN": ""},
                body: params,
            };

            try {
                // 发起请求
                const {data, error} = await useFetch("user/signUp", requestOptions);

                // 处理响应数据
                if (!error.value) {
                    return {data: data.value, error: null};
                }

                return {data: null, error: error};
            } catch (err) {
                console.error('request error', err);
                return {data: null, error: err};
            }
        },
        async signOut() {
            this._id = ""
            this.nickname = ""
            this.avatar = ""
            this.loginLog = {}
        }
    }
})